import React, { lazy, Suspense } from 'react';
import type { RouteObject } from 'react-router-dom';
import type { MenuProps } from '@nbase/ui';
import type { MenuTree } from '~/services/menu.service';
import { MENU_TYPE } from '~/services/menu.service';
import * as Icons from '@nbase/ui/icons';

/**
 * 组件路径映射
 * 将菜单的 component 字段映射到实际的组件路径
 */
const COMPONENT_MAP: Record<string, React.LazyExoticComponent<React.ComponentType<any>>> = {
  // 系统管理
  'System/User': lazy(() => import('~/pages/System/User')),
  'System/Role': lazy(() => import('~/pages/System/Role')),
  'System/Menu': lazy(() => import('~/pages/System/Menu')),
  'System/Dict': lazy(() => import('~/pages/System/Dict')),
  'System/Dept': lazy(() => import('~/pages/System/Dept')),
  'System/Post': lazy(() => import('~/pages/System/Post')),
  'System/AuditLog': lazy(() => import('~/pages/System/AuditLog')),

  // 首页
  'Home': lazy(() => import('~/pages/Home')),
};

/**
 * 根据组件路径获取懒加载组件
 */
function getComponent(componentPath: string | null | undefined): React.ReactNode {
  if (!componentPath) {
    return null;
  }

  const Component = COMPONENT_MAP[componentPath];
  if (!Component) {
    console.warn(`组件路径 "${componentPath}" 未在 COMPONENT_MAP 中找到`);
    return null;
  }

  return (
    <Suspense>
      <Component />
    </Suspense>
  );
}

/**
 * 根据图标名称获取图标组件
 */
function getIcon(iconName: string | null | undefined): React.ReactNode {
  if (!iconName) {
    return null;
  }

  // 从 Icons 中获取对应的图标组件
  const IconComponent = (Icons as any)[iconName];
  if (!IconComponent) {
    console.warn(`图标 "${iconName}" 未在 @nbase/ui/icons 中找到`);
    return null;
  }

  return React.createElement(IconComponent);
}

/**
 * 将菜单树转换为 React Router 路由配置
 * 只处理菜单类型（type = 1），忽略按钮类型（type = 2）
 */
export function generateRoutesFromMenus(menus: MenuTree[]): RouteObject[] {
  const routes: RouteObject[] = [];

  for (const menu of menus) {
    // 只处理菜单类型
    if (menu.type !== MENU_TYPE.MENU) {
      continue;
    }

    // 如果有 path 和 component，生成路由
    if (menu.path && menu.component) {
      // 移除路径开头的斜杠，转换为相对路径
      const relativePath = menu.path.startsWith('/') ? menu.path.slice(1) : menu.path;

      routes.push({
        path: relativePath,
        element: getComponent(menu.component),
      });
    }

    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      const childRoutes = generateRoutesFromMenus(menu.children);
      routes.push(...childRoutes);
    }
  }

  return routes;
}

/**
 * 从菜单树中提取路由元数据（用于面包屑）
 */
export interface RouteMetaInfo {
  title: string;
  icon?: string;
  parent?: string;
  keepAlive?: boolean;
}

export function extractRouteMetaFromMenus(menus: MenuTree[]): Record<string, RouteMetaInfo> {
  const metaMap: Record<string, RouteMetaInfo> = {};

  function traverse(menuList: MenuTree[], parentPath?: string) {
    for (const menu of menuList) {
      // 只处理菜单类型
      if (menu.type !== MENU_TYPE.MENU) {
        continue;
      }

      if (menu.path) {
        metaMap[menu.path] = {
          title: menu.name,
          icon: menu.icon || undefined,
          parent: parentPath,
          keepAlive: menu.keepAlive,
        };
      }

      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        traverse(menu.children, menu.path || parentPath);
      }
    }
  }

  traverse(menus);
  return metaMap;
}

/**
 * 将菜单树转换为 Ant Design Menu 组件需要的格式
 */
export function convertMenusToAntdMenuItems(
  menus: MenuTree[],
  navigate: (path: string) => void
): MenuProps['items'] {
  return menus
    .filter((menu) => menu.type === MENU_TYPE.MENU && menu.visible)
    .map((menu) => {
      const item: any = {
        key: menu.path || menu.id,
        label: menu.name,
        icon: getIcon(menu.icon), // 添加图标
      };

      // 如果有子菜单，递归处理
      if (menu.children && menu.children.length > 0) {
        item.children = convertMenusToAntdMenuItems(menu.children, navigate);
      } else if (menu.path) {
        // 叶子节点才添加点击事件
        item.onClick = () => navigate(menu.path!);
      }

      return item;
    });
}

